package com.example.studentmanagement.controller;

import com.example.studentmanagement.entity.Classes;
import com.example.studentmanagement.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 〈功能概述〉<br>
 *
 * @className: ClassController
 * @author: 程序员Mars
 * @date: 2024/12/26 20:26
 */
@Controller
@RequestMapping("/class")
public class ClassController {


    @Autowired
    private ClassService classService;

    /**
     * 显示班级列表
     */
    @GetMapping("/list")
    public String listClasses(Model model) {
        List<Classes> classes = classService.getAllClasses();
        model.addAttribute("classes", classes);
        return "class/class-list";
    }

    /**
     * 跳转到新增班级页面
     */
    @GetMapping("/create")
    public String createClassForm(Model model) {
        model.addAttribute("cls", new Classes());
        return "class/class-form";
    }

    /**
     * 跳转到编辑班级页面
     */
    @GetMapping("/edit/{id}")
    public String editClassForm(@PathVariable("id") Integer id, Model model) {
        Classes cls = classService.getClassById(id);
        model.addAttribute("cls", cls);
        return "class/class-form";
    }

    /**
     * 保存或更新班级
     */
    @PostMapping("/save")
    public String saveClass(@ModelAttribute Classes cls) {
        if (cls.getId() == null) {
            classService.createClass(cls); // 新增
        } else {
            classService.updateClass(cls); // 更新
        }
        return "redirect:/class/list";
    }

    /**
     * 删除班级
     */
    @GetMapping("/delete/{id}")
    public String deleteClass(@PathVariable("id") Integer id) {
        classService.deleteClass(id);
        return "redirect:/class/list";
    }

}